package engine

import (
	"HSP/modules/file"
	"HSP/modules/http"
	"errors"
	"github.com/dop251/goja_nodejs/console"
	"github.com/dop251/goja_nodejs/require"
	"github.com/dop251/goja_nodejs/util"
	"io/ioutil"
	"os"
	"path/filepath"
	"syscall"
)

func InitEngineFunction() {

	registry := require.NewRegistry(
		require.WithGlobalFolders("."),
		require.WithLoader(hspSourceLoader),
	)
	registry.RegisterNativeModule("http", http.Require)
	registry.RegisterNativeModule("file", file.Require)
	registry.RegisterNativeModule("console", console.Require)
	registry.RegisterNativeModule("util", util.Require)
	registry.Enable(Engine)
	//全局启用,console,util默认就启用，所有不用管，自定义库的时候按需导入，默认都不全局 因此，js需要手动导入 如 var http = require("http")
	//http.Enable(Engine)
	//file.Enable(Engine)
}

/**
解决模块位置问题。
*/
func hspSourceLoader(filename string) ([]byte, error) {
	data, err := ioutil.ReadFile(filepath.FromSlash(Path + filename))
	if err != nil {
		if os.IsNotExist(err) || errors.Is(err, syscall.EISDIR) {
			err = require.ModuleFileDoesNotExistError
		}
	}
	return data, err
}
